package com.example.maple.ccsclient.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Scroller;

/**
 * Created by maple on 2016/8/8.
 */
public class SlidingBaseView extends RelativeLayout implements View.OnTouchListener {


	/**
	 * SlidingBaseView布局的父布局
	 */
	private ViewGroup mParentView;
	/**
	 * 处理滑动逻辑的View
	 */
	private View touchView;
	/**
	 * 滑动的最小距离
	 */
	private int mTouchSlop;
	/**
	 * 按下点的X坐标
	 */
	private float downX;
	/**
	 * 按下点的Y坐标
	 */
	private float downY;
	/**
	 * 临时存储X坐标
	 */
	private float tempX;
	/**
	 * 滑动类
	 */
	private Scroller mScroller;
	/**
	 * SlidingBaseView的宽度
	 */
	private int viewWidth;
	/**
	 * 记录是否正在滑动
	 */
	private boolean isSliding;


	//手指向右滑动时的最小速度
	private static final int XSPEED_MIN = 200;

	//手指向右滑动时的最小距离
	private static final int XDISTANCE_MIN = 150;


	//记录手指移动时的横坐标。
	private float moveX;

	//用于计算手指滑动的速度。
	private VelocityTracker mVelocityTracker;

	private OnSlidingFinishListener mOnSlidingFinishListener;
	private boolean isFinish;


	public SlidingBaseView(Context context) {
		this(context,null);
	}

	public SlidingBaseView(Context context, AttributeSet attrs) {
		this(context, attrs,0);
	}

	public SlidingBaseView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
		mScroller = new Scroller(context);
	}

	@Override
	protected void onLayout(boolean changed, int l, int t, int r, int b) {
		super.onLayout(changed, l, t, r, b);
		if (changed) {
			// 获取SlidingFinishLayout所在布局的父布局
			mParentView = (ViewGroup) this.getParent();
			viewWidth = this.getWidth();
		}
	}

	/**
	 * 设置OnSildingFinishListener, 在onSlidingFinish()方法中finish Activity
	 *
	 * @param onSlidingFinishListener
	 */
	public void setOnSildingFinishListener(
			OnSlidingFinishListener onSlidingFinishListener) {
		this.mOnSlidingFinishListener = onSlidingFinishListener;
	}

	/**
	 * 设置Touch的View
	 *
	 * @param touchView
	 */
	public void setTouchView(View touchView) {
		this.touchView = touchView;
		touchView.setOnTouchListener(this);
	}

	public View getTouchView() {
		return touchView;
	}


	@Override
	public boolean onTouch(View v, MotionEvent event) {

		switch (event.getAction()) {

			case MotionEvent.ACTION_DOWN: {
				downX = tempX = event.getRawX();
				downY = event.getRawY();
				break;
			}

			case MotionEvent.ACTION_MOVE: {
				moveX = event.getRawX();

				float deltaX = tempX - moveX;
				tempX = moveX;
				if (Math.abs(moveX - downX) > mTouchSlop
						&& Math.abs((int) event.getRawY() - downY) < mTouchSlop) {
					isSliding = true;

					// 若touchView是AbsListView，
					// 则当手指滑动，取消item的点击事件，不然我们滑动也伴随着item点击事件的发生
					if (isTouchOnAbsListView()) {
						MotionEvent cancelEvent = MotionEvent.obtain(event);
						cancelEvent.setAction(MotionEvent.ACTION_CANCEL
								| (event.getActionIndex() << MotionEvent.ACTION_POINTER_INDEX_SHIFT));
						v.onTouchEvent(cancelEvent);
					}

				}

				if (moveX - downX >= 0 && isSliding) {
					mParentView.scrollBy((int) deltaX, 0);
					// 屏蔽在滑动过程中ListView ScrollView等自己的滑动事件
					if (isTouchOnScrollView() || isTouchOnAbsListView()) {
						return true;
					}
				}



				break;
			}

			case MotionEvent.ACTION_UP: {
				isSliding = false;
				if (mParentView.getScrollX() <= -viewWidth / 2) {
					isFinish = true;
					scrollRight();
				} else {
					scrollOrigin();
					isFinish = false;
				}

				recycleVelocityTracker();

				break;
			}

			default:
				break;
		}

		return false;
	}

	//滚动到起始位置
	private void scrollOrigin() {
		int delta = mParentView.getScrollX();
		mScroller.startScroll(mParentView.getScrollX(), 0, -delta, 0,
				Math.abs(delta));
		postInvalidate();
	}

	//滚出界面
	private void scrollRight() {
		final int delta = (viewWidth + mParentView.getScrollX());
		// 调用startScroll方法来设置一些滚动的参数，我们在computeScroll()方法中调用scrollTo来滚动item
		mScroller.startScroll(mParentView.getScrollX(), 0, -delta + 1, 0,
				Math.abs(delta));
		postInvalidate();
	}

	private boolean isTouchOnScrollView() {
		return touchView instanceof ScrollView;
	}

	private boolean isTouchOnAbsListView() {
		return touchView instanceof AbsListView;
	}


	@Override
	public void computeScroll() {
		// 调用startScroll的时候scroller.computeScrollOffset()返回true，
		if (mScroller.computeScrollOffset()) {
			mParentView.scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
			postInvalidate();
			if (mScroller.isFinished()) {

				if (mOnSlidingFinishListener != null && isFinish) {
					mOnSlidingFinishListener.onSlidingFinish();
				}
			}
		}
	}


	private void createVelocityTracker(MotionEvent event) {
		if (mVelocityTracker == null) {
			mVelocityTracker = VelocityTracker.obtain();
		}
		mVelocityTracker.addMovement(event);
	}

	/**
	 * 回收VelocityTracker对象。
	 */
	private void recycleVelocityTracker() {
		mVelocityTracker.recycle();
		mVelocityTracker = null;
	}

	/**
	 * 获取手指在content界面滑动的速度。
	 *
	 * @return 滑动速度，以每秒钟移动了多少像素值为单位。
	 */
	private int getScrollVelocity() {
		mVelocityTracker.computeCurrentVelocity(1000);
		int velocity = (int) mVelocityTracker.getXVelocity();
		return Math.abs(velocity);
	}

	/*
		* 滑动完成时候接口
		* */
	public interface OnSlidingFinishListener {
		void onSlidingFinish();
	}
}
